package com.xhsj.user.pms.patent.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhsj.user.pms.patent.domain.*;
import com.xhsj.user.pms.patent.mapper.*;
import com.xhsj.user.pms.patent.query.*;
import com.xhsj.user.pms.patent.service.BillService;
import com.xhsj.user.pms.patent.service.PatentService;
import com.xhsj.user.pms.patent.service.TbPamJudgesIprService;
import com.xhsj.user.pms.workflow.controller.WorkFlowController;
import com.xhsj.user.pms.workflow.dto.ExecProgressDto;
import com.xhsj.user.pms.workflow.model.RuningTaskModel;
import com.xhsj.user.pms.workflow.service.WorkflowExecService;
import com.xhsj.user.utils.IdGen;
import com.xhsj.user.utils.StringUtils;
import com.xhsj.user.utils.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 苏小林
 * @Description
 * @createTime 2020年02月20日 10:41:00
 */
@Slf4j
@Service
public class PatentServiceImpl implements PatentService {
    @Autowired
    private PatentMapper patentMapper;

    @Autowired
    private BillService billService;

    @Autowired
    private BillMapper billMapper;

    @Autowired
    private WorkflowExecService workflowExecService;

    @Autowired
    private PatentFileMapper patentFileMapper;

    @Autowired
    private JudgesMapper judgesMapper;

    @Autowired
    private JudgesUserMapper judgesUserMapper;

    @Autowired
    private DisclosureMapper disclosureMapper;
    @Autowired
    private TbPamJudgesIprService tbPamJudgesIprService;

    @Autowired
    private PatentApplyProjectMapper patentApplyProjectMapper;
    @Autowired
    private PatentApplyFilePageMapper patentApplyFilePageMapper;
    @Autowired
    private PatentApplyCostMapper patentApplyCostMapper;
    @Autowired
    private TbPamPatentOverseasFileMapper tbPamPatentOverseasFileMapper;
    @Autowired
    private TbPamInventorProposalIprMapper tbPamInventorProposalIprMapper;
    @Autowired
    private DisclosureInventorMapper disclosureInventorMapper;

    @Override
    public void save(Map<String, Object> param) throws Exception {

        ExecProgressDto execProgressDto = new ExecProgressDto();
        execProgressDto.setDisclosureId(StringUtils.getStringValue(param,"disclosureId"));
        execProgressDto.setNodeId(StringUtils.getStringValue(param,"nodeId"));
        execProgressDto.setNodeName(StringUtils.getStringValue(param,"nodeName"));
        execProgressDto.setFullName(UserUtils.getLoginAppUser().getFullName());
        execProgressDto.setProcessTaskId(StringUtils.getStringValue(param,"processTaskId"));

        Long userId = Long.valueOf(String.valueOf(param.get("userId")));
        Patent patent = StringUtils.toJavaBean(param, Patent.class);
        workflowExecService.execProgress2(execProgressDto);
        patent.setDelFlag(0);
        patent.setUpdateTime(new Date());
        patent.setUpdateBy(userId);
        if (StringUtils.isBlank(patent.getId())) {// 新增
            patent.setId(IdGen.generateUUID());
            patent.setCreatedBy(userId);
            patent.setCreatedDate(new Date());
            patentMapper.insert(patent);
        } else {
            patentMapper.updateById(patent);
        }
        List<PatentFile> patentFileList = patent.getPatentFileList();
        for (PatentFile patentFile : patentFileList) {
            patentFile.setPatentFileId(IdGen.generateUUID());
            patentFile.setPatentId(patent.getId());
            patentFileMapper.insert(patentFile);
        }

    }

    @Override
    //根据内部编号修改专利文件
    public int updatePatenByNum(Patent patent) {
        patent.setUpdateTime(new Date());
        return patentMapper.updatePatenByNum(patent);
    }

    //    保存已有的专利
    @Override
    public int saveAlreadyExistingPatent(Map<String, Object> param) {
        int i = 0;
        Long userId = Long.valueOf(String.valueOf(param.get("userId")));
        Bill bill = StringUtils.toJavaBean(param, Bill.class);
        //保存到专利表中
        Patent patent = StringUtils.toJavaBean(param, Patent.class);
        patent.setDelFlag(0);
        patent.setUpdateTime(new Date());
        patent.setUpdateBy(userId);
        if (StringUtils.isBlank(patent.getId())) {// 新增
            patent.setId(IdGen.generateUUID());
            patent.setCreatedBy(userId);
            patent.setCreatedDate(new Date());
            i = patentMapper.insert(patent);
        } else {
            i = patentMapper.updateById(patent);
        }
        if (i != 1) {
            return 0;
        }
        //保存到费用表中
        if (StringUtils.isBlank(bill.getBillInformId())) {
            bill.setBillForDisclosure(patent.getId());
            bill.setBillInformId(IdGen.generateUUID());
            bill.setCreatedUser(userId);
//            bill.setEnewTime(patent.getYearFeePayTime());
//            bill.setExpireTime(patent.getReneTime());
//            bill.setBillAmount(patent.getYearFeePayAmount());
            bill.setBillType(1);
            return billService.saveBill(bill);
        } else {
            //修改费用表
            return billMapper.updateById(bill);
        }


    }

    @Override
    public IPage<Map<String, Object>> findPatentList(PatentFindPatentListQuery param) {
        IPage<Map<String, Object>> list =new Page<Map<String, Object>>();
        Page<Map<String, Object>> page = new Page<>(param.getPageNum(),param.getPageSize());
        String phaseStatus = param.getPhaseStatus();
        List<Map<String, Object>> records = new ArrayList<>();
        if (!Objects.isNull(phaseStatus)) {
            List<String> phaseStatusList = new ArrayList<>();
            phaseStatusList.add(phaseStatus);
                list = patentMapper.findDiscList(page,param,phaseStatusList,phaseStatus);
                records = list.getRecords();
        }


//        List<String> collect = records.stream().map(item -> String.valueOf(item.get("disclosureId"))).collect(Collectors.toList());
//        if(collect != null && collect.size() != 0) {
//            Map<String,Map<String,String>> judgesById = judgesMapper.getJudgesById(collect);
//            records.forEach(record -> {
//                if (judgesById.containsKey(String.valueOf(record.get("disclosureId")))) {
//                    record.put("judgesName",judgesById.get(String.valueOf(record.get("disclosureId"))).get("judgesName"));
//                }
//            });
//        }
        getOperationer(records);
        return list;
    }
    public void getOperationer(List<Map<String, Object>> records){
        // 获取对应交底书id数组
        List<String> disclosureIdList = records.stream().map(item -> String.valueOf(item.get("disclosureId"))).collect(Collectors.toList());
        if(StringUtils.isNotBlank(disclosureIdList) && disclosureIdList.size() !=0 ) {
            // 发明人
            Map<String, InventorListQuery> inventorList = disclosureInventorMapper.getInventorList(disclosureIdList);
            // 获取操作人通过底书id
            Map<String, OperationerListQuery> adviceIprList = tbPamInventorProposalIprMapper.getAdviceIprList(disclosureIdList);
            records.forEach(item -> {
                if (adviceIprList.containsKey(String.valueOf(item.get("disclosureId"))) && !"003BFA10D8934DF992E34DED81787CCC".equals(String.valueOf(item.get("nodeId"))) && !"19181F68A04841F2AE079A8D52925200".equals(String.valueOf(item.get("nodeId")))) {
                    item.put("conveyancer", adviceIprList.get(String.valueOf(item.get("disclosureId"))).getFullName());
                    item.put("conveyancerId", adviceIprList.get(String.valueOf(item.get("disclosureId"))).getUserId());
                }
                if (inventorList.containsKey(String.valueOf(item.get("disclosureId")))){
                    item.put("inventor",(inventorList.get(String.valueOf(item.get("disclosureId"))).getInventor()));
                }
            });

            // 获取操作人通过底书id
//            Map<String, OperationerListQuery> operationerList = patentFileMapper.getOperationerList(disclosureIdList);
//            records.forEach(item -> {
//                if (operationerList.containsKey("3-" + String.valueOf(item.get("disclosureId")))) {
//                    item.put("conveyancer", operationerList.get("3-" + String.valueOf(item.get("disclosureId"))).getFullName());
//                    item.put("conveyancerId", operationerList.get("3-" + String.valueOf(item.get("disclosureId"))).getUserId());
//                }
//                else if (operationerList.containsKey("1-" + String.valueOf(item.get("disclosureId")))) {
//                    item.put("conveyancer", operationerList.get("1-" + String.valueOf(item.get("disclosureId"))).getFullName());
//                    item.put("conveyancerId", operationerList.get("1-" + String.valueOf(item.get("disclosureId"))).getUserId());
//                }
//            });
//            System.out.println(records);
        }
    }


    @Override
    public IPage<Map<String, Object>> findPiePatentList(PatentFindPatentListQuery param){
        IPage<Map<String, Object>> list=new Page<>();
        String phaseStatus = param.getPhaseStatus();
        Page<Map<String, Object>> page = new Page<>(param.getPageNum(),param.getPageSize());
        if (!Objects.isNull(phaseStatus)) {
            List<String> phaseStatusList = new ArrayList<>();
            phaseStatusList.add(phaseStatus);
            if ("3".equals(phaseStatus)) {
                phaseStatusList.add("10");
            }
            if ("4".equals(phaseStatus)) {
                phaseStatusList.add("11");
            }
            if ("10".equals(phaseStatus) || "11".equals(phaseStatus)) {
                return list;
            }

            list = patentMapper.findDiscList(page,param,phaseStatusList,phaseStatus);
            List<Map<String, Object>> records = list.getRecords();
            for (Map<String, Object> map:records) {
                if("10".equals(map.get("phaseStatus"))){
                    map.put("phaseStatus","3");
                }
                if("11".equals(map.get("phaseStatus"))){
                    map.put("phaseStatus","4");
                }
            }
            // 技术领域
//            List<String> collect = records.stream().map(item -> String.valueOf(item.get("disclosureId"))).collect(Collectors.toList());
//            if(collect != null && collect.size() != 0) {
//                Map<String,Map<String,String>> judgesById = judgesMapper.getJudgesById(collect);
//                records.forEach(record -> {
//                    if (judgesById.containsKey(String.valueOf(record.get("disclosureId")))) {
//                        record.put("judgesName",judgesById.get(String.valueOf(record.get("disclosureId"))).get("judgesName"));
//                    }
//                });
//            }
            this.getOperationer(records);
        }

        return list;
    }



    // 二级报表查询专利文件列表
    @Override
    public IPage<Map<String, Object>> findPatentListPie(PatentFindPatentListQuery param){
        String userId = param.getUserId();
        String startDate = param.getStartDate();
        String endDate = param.getEndDate();
        String archivesNum = param.getArchivesNum();
        Page<Map<String, Object>> page=new Page(param.getPageNum(),param.getPageSize());
        IPage<Map<String, Object>> patentListPie = null;
        List<String> nodeIdList=new ArrayList<>();
        switch (param.getPhaseStatus()){
            case "0":
                nodeIdList.add("003BFA10D8934DF992E34DED81787CCC");
                nodeIdList.add("3AE5CBF5E43E444D8256929EC6BFF2C8");
                nodeIdList.add("67409ADFDC384E46AA3F6B410113E495");
                nodeIdList.add("D83445C2BFAA4B1CBA275DD1640D3EFE");
                nodeIdList.add("88A4B87FDF314252902F8FA65B2358BC");
                nodeIdList.add("88c90b93b2894fe5bd17bb7e3dca6f24");
                nodeIdList.add("253CBECAAB5342CBA4EFC3FE56B1F34C");
                nodeIdList.add("97BF5B1F73414EA9BBDB55C62D46B981");
                nodeIdList.add("7524DFC3666B40C5A6E6EEFD063F06EA");
                break;
            case "3":
                nodeIdList.add("003BFA10D8934DF992E34DED81787CCC");
                break;
            case "4":
                nodeIdList.add("3AE5CBF5E43E444D8256929EC6BFF2C8");
                break;
            case "5":
                nodeIdList.add("67409ADFDC384E46AA3F6B410113E495");
                break;
            case "6":
                nodeIdList.add("D83445C2BFAA4B1CBA275DD1640D3EFE");
                break;
            case "7":
                nodeIdList.add("88A4B87FDF314252902F8FA65B2358BC");
                break;
            case "8":
                nodeIdList.add("88c90b93b2894fe5bd17bb7e3dca6f24");
                break;
            case "9":
                nodeIdList.add("253CBECAAB5342CBA4EFC3FE56B1F34C");
                break;
            case "10":
                nodeIdList.add("97BF5B1F73414EA9BBDB55C62D46B981");
                break;
            case "11":
                nodeIdList.add("7524DFC3666B40C5A6E6EEFD063F06EA");
                break;
        }
        if ("3".equals(param.getPhaseStatus())) {
            // 二级报表查询节点为交底书专利文件列表
            patentListPie = patentMapper.findPatentDisclosureListPie(page,userId, startDate, endDate, archivesNum,param.getPhaseStatus(),nodeIdList,param);
        }else {
            // 二级报表查询专利文件列表
              patentListPie = patentMapper.findPatentListPie(page, userId, startDate, endDate,
                    archivesNum, param.getPhaseStatus(), nodeIdList, param);
            if ("0".equals(param.getPhaseStatus())) {
                List<Map<String, Object>> records = patentListPie.getRecords();
                for (Map<String, Object> record : records) {
                    if ("D83445C2BFAA4B1CBA275DD1640D3EFE".equals(record.get("nodeId"))) {
                        record.put("phaseStatus", "6");
                    } else if ("88A4B87FDF314252902F8FA65B2358BC".equals(record.get("nodeId"))) {
                        record.put("phaseStatus", "7");
                    } else if ("88c90b93b2894fe5bd17bb7e3dca6f24".equals(record.get("nodeId"))) {
                        record.put("phaseStatus", "8");
                    } else if ("253CBECAAB5342CBA4EFC3FE56B1F34C".equals(record.get("nodeId"))) {
                        record.put("phaseStatus", "9");
                    }
                }
            }
        }
        List<Map<String, Object>> records = patentListPie.getRecords();
        // 技术领域
//        List<String> collect = records.stream().map(item -> String.valueOf(item.get("disclosureId"))).collect(Collectors.toList());
//        if(collect != null && collect.size() != 0) {
//            Map<String,Map<String,String>> judgesById = judgesMapper.getJudgesById(collect);
//            records.forEach(record -> {
//                if (judgesById.containsKey(String.valueOf(record.get("disclosureId")))) {
//                    record.put("judgesName",judgesById.get(String.valueOf(record.get("disclosureId"))).get("judgesName"));
//                }
//            });
//        }
        this.getOperationer(records);
        return patentListPie;
    }

    @Override
    public IPage<Patent> findList(Map<String, Object> param) {
        int pageNum = 1;
        int pageSize = 20;
        if (StringUtils.isNotNull(param.get("pageNum")))
            pageNum = Integer.parseInt(String.valueOf(param.get("pageNum")));
        if (StringUtils.isNotNull(param.get("pageSize")))
            pageSize = Integer.parseInt(String.valueOf(param.get("pageSize")));
        IPage<ExamineModel> page = new Page<>(pageNum, pageSize);
        String name = Objects.isNull(param.get("name")) ? "" : String.valueOf(param.get("name"));
        String status = Objects.isNull(param.get("status")) ? "" : String.valueOf(param.get("status"));
        return patentMapper.findList(page,name, status);
    }

    // 定时监听 优先权届满日 PCT进入国家 香港登记Step1 香港登记Step2 澳门登记 提示
//    public IPage<TimeLimitNameQuery> monitorList(Map<String,Integer> param) {
        // 获取专利模块海外地区时间详情表
//        Page<TimeLimitNameQuery> page=new Page(param.get("pageNum"),param.get("pageSize"));
//        List<TbPamOverseasRegionalDetails> list = tbPamOverseasRegionalDetailsService.list();
//        return tbPamOverseasRegionalDetailsService.getTimeLimitName(page,list);
//        for (TbPamOverseasRegionalDetails tbPamOverseasRegionalDetails:list) {
            // 查询各个状态监听的时间点
            // 关联的表名
//            String relationTable = tbPamOverseasRegionalDetails.getRelationTable();
//            // 关联表名对应的字段
//            String timeLimitName = tbPamOverseasRegionalDetails.getTimeLimitName();
//            // 提醒点(月)
//            int reminderPoint = tbPamOverseasRegionalDetails.getReminderPoint();
//            // 期限(月)
//            int term = tbPamOverseasRegionalDetails.getTerm();
//            Page<TimeLimitNameQuery> page=new Page(param.get("pageNum"),param.get("pageSize"));
//            List<TimeLimitNameQuery> timeLimitDateList = tbPamOverseasRegionalDetailsService.getTimeLimitName(page,relationTable,timeLimitName,reminderPoint,term);
//            for (TimeLimitNameQuery timeLimitDates:timeLimitDateList) {

//                Date timeLimitDate = timeLimitDates.getTimeLimitName();
//                // 提醒点(月)转日期
//                Calendar calendarReminderPoint = Calendar.getInstance();
//                calendarReminderPoint.setTime(timeLimitDate);
//                calendarReminderPoint.add(Calendar.MONTH,-reminderPoint);// 日期减个月
//                Date timeReminderPoint = calendarReminderPoint.getTime();
//                // 期限(月)转日期
//                Calendar calendarTerm = Calendar.getInstance();
//                calendarTerm.setTime(timeLimitDate);
//                calendarTerm.add(Calendar.MONTH,-term);// 日期减个月
//                Date timeTerm = calendarTerm.getTime();
//                if ((new Date().after(timeReminderPoint) || new Date().equals(timeReminderPoint)) && (new Date().before(timeTerm) || new Date().equals(timeTerm))) {
//                    //
//                }
//            }


//        }

//    }

    @Transactional(rollbackFor=Exception.class)
   public void saveJudges(Map<String, Object> param) throws Exception {
       List<List<Long>> users = (List<List<Long>>) param.get("userList");
       String createdUser = String.valueOf(param.get("createdUser"));
       Judges judges = StringUtils.toJavaBean(param, Judges.class);
       if (StringUtils.isBlank(judges.getId())) {
           judges.setId(IdGen.generateUUID());
           judges.setCreateBy(createdUser);
           judges.setCreateDate(new Date());
           judges.setUpdateBy(createdUser);
           judges.setUpdateDate(new Date());
           judges.setDelFlag(0);
           int insert = judgesMapper.insert(judges);
           if (insert == 0) {
               throw new Exception("保存失败,保存返回值为0");
           }
       } else {
           int i = judgesMapper.updateById(judges);
           // 删除评审会成员
           judgesUserMapper.deleteByJudgesId(judges.getId());
           if (i == 0) {
               throw new Exception("修改评审会信息失败,保存返回值为0");
           }
           // 修改节点为评审会初审终审，评审会初审终审确认的指派人
           // 查询是否有当前节点在评审会初审和终审以及评审会初审确认和终审确认
           List<RuningTaskModel> runingTask = disclosureMapper.getRuningTask(judges.getId());
           workflowExecService.updateIdentityAndHi(judges.getPatentUserId(), users,runingTask,null);
       }

       if (users != null && !users.isEmpty()) {
           for (List<Long> user : users) {
               JudgesUser judgesUser = new JudgesUser();
               judgesUser.setId(IdGen.generateUUID());
               judgesUser.setJudgesId(judges.getId());
               judgesUser.setDeptId(StringUtils.toLong(user.get(0)));
               judgesUser.setUserId(StringUtils.toLong(user.get(1)));
               judgesUser.setCreateBy(createdUser);
               judgesUser.setCreateDate(new Date());
               judgesUser.setUpdateBy(createdUser);
               judgesUser.setUpdateDate(new Date());
               judgesUser.setDelFlag(0);
               int insert1 = judgesUserMapper.insert(judgesUser);
               if (insert1 == 0) {
                   throw new Exception("修改评审会成员失败,保存返回值为0");
               }

           }
       }
       //保存技术领域对应的ipr
       //删除技术领域对应的ipr根据技术领域的id
       tbPamJudgesIprService.deleteByJudgesId(judges.getId());
       List<String> iprList = judges.getIprList();
       if (iprList.size() > 0) {
           for (String ipr : iprList) {
               TbPamJudgesIpr tbPamJudgesIpr = new TbPamJudgesIpr();
               tbPamJudgesIpr.setJudgesId(judges.getId());
               tbPamJudgesIpr.setUserId(ipr);
               tbPamJudgesIpr.setCreateBy(createdUser);
               tbPamJudgesIpr.setUpdateBy(createdUser);
               if (!tbPamJudgesIprService.save(tbPamJudgesIpr)) {
                   throw new Exception("保存技术领域对应的ipr失败");
               }
           }

       }
    }

    public void savePatentInfo(Map<String,Object> param) throws Exception {
        Long userId = UserUtils.getLoginAppUser().getUserId();
        PatentApplyProject patentApplyProject = StringUtils.toJavaBean(param, PatentApplyProject.class);
        patentApplyProject.setCreatedBy(userId);
        patentApplyProject.setCreatedDate(new Date());
        patentApplyProject.setDelFlag(0);
        int insert=0;
        if (StringUtils.isBlank(patentApplyProject.getId())) {// 新增
            patentApplyProject.setId(IdGen.generateUUID());
            insert=patentApplyProjectMapper.insert(patentApplyProject);
            }else{
            insert=patentApplyProjectMapper.updateById(patentApplyProject);
        }
        if (insert != 1) {
            log.error("保存专利申请项目主表出错");
            throw new Exception("保存专利申请项目主表出错");
        }

        // 删除对应的专利申请文件页数根据项目id
        patentApplyFilePageMapper.deleteByProjectId(patentApplyProject.getId());
        List<PatentApplyFilePageQuery> patentApplyFilePageList = patentApplyProject.getPatentApplyFilePageList();
        if (!patentApplyFilePageList.isEmpty()) {
            for (PatentApplyFilePageQuery patentApplyFilePage : patentApplyFilePageList) {
                patentApplyFilePage.setId(IdGen.generateUUID());
                patentApplyFilePage.setApplyProjectId(patentApplyProject.getId());
                patentApplyFilePage.setCreatedBy(userId);
                patentApplyFilePage.setCreatedDate(new Date());
                patentApplyFilePage.setDelFlag(0);
                PatentApplyFilePage patentApplyFilePage1 = new PatentApplyFilePage();
                BeanUtils.copyProperties(patentApplyFilePage,patentApplyFilePage1);
                if (StringUtils.isBlank(patentApplyFilePage.getPageNum()))
                    patentApplyFilePage1.setPageNum("");
                else
                    patentApplyFilePage1.setPageNum(String.valueOf(patentApplyFilePage.getPageNum()));
                int insert1 = patentApplyFilePageMapper.insert(patentApplyFilePage1);
                if (insert1 != 1) {
                    log.error("保存专利申请项目文件出错");
                    throw new Exception("保存专利申请项目文件出错");
                }
            }
        }

        Patent patent = patentApplyProject.getPatentList();
        if (patent != null) {
            patent.setDelFlag(0);
            patent.setUpdateTime(new Date());
            patent.setUpdateBy(userId);
            if (StringUtils.isBlank(patent.getId())) {// 新增
                patent.setId(IdGen.generateUUID());
                patent.setCreatedBy(userId);
                patent.setCreatedDate(new Date());
                patentMapper.insert(patent);
            } else {
                patentMapper.updateById(patent);
            }
        }

        // 删除根据apply_project_id
        patentApplyCostMapper.deleteByApplyProjectId(patentApplyProject.getId());
        List<PatentApplyCostQuery> patentApplyCostList = patentApplyProject.getPatentApplyCostList();
        if (!patentApplyCostList.isEmpty()) {
            for (PatentApplyCostQuery patentApplyCost : patentApplyCostList) {
                patentApplyCost.setApplyProjectId(patentApplyProject.getId());
                patentApplyCost.setId(IdGen.generateUUID());
                patentApplyCost.setCreatedBy(userId);
                patentApplyCost.setCreatedDate(new Date());
                patentApplyCost.setDelFlag(0);
                PatentApplyCost patentApplyCost1 = new PatentApplyCost();
                BeanUtils.copyProperties(patentApplyCost,patentApplyCost1);
                if (StringUtils.isBlank(patentApplyCost.getAmount()))
                    patentApplyCost1.setAmount(null);
                else
                    patentApplyCost1.setAmount(String.valueOf(patentApplyCost.getAmount()));
                int insert1 = patentApplyCostMapper.insert(patentApplyCost1);
                if (insert1 != 1) {
                    log.error("保存专利申请项目费用出错");
                    throw new Exception("保存专利申请项目费用出错");
                }
            }
        }

        List<Integer> fileTypeList=new ArrayList<>();
        fileTypeList.add(5);
        // 删除对应的文件根据DiscId
        patentFileMapper.deleteByDiscId(patentApplyProject.getId(),fileTypeList);
        // 删除对应的文件根据PatentId
        List<Integer> fileTypeList2=new ArrayList<>();
        fileTypeList2.add(6);
        fileTypeList2.add(7);
        patentFileMapper.deleteByPatentId(patent.getId(),fileTypeList2);
        // 删除答复文件
        tbPamPatentOverseasFileMapper.deleteByDataId(patentApplyProject.getDisclosureId());
        List<PatentFile> patentFileList = patentApplyProject.getPatentApplyFileList();
        List<PatentFile> fileList1 = patent.getFileList1();
        List<PatentFile> fileList2 = patent.getFileList2();
        patentFileList.addAll(fileList1);
        patentFileList.addAll(fileList2);
        if (!patentFileList.isEmpty()) {
            for (PatentFile patentFile : patentFileList) {
                if ("2".equals(String.valueOf(patentFile.getUploadType()))) {
                    TbPamPatentOverseasFile tbPamPatentOverseasFile = new TbPamPatentOverseasFile();
                    BeanUtils.copyProperties(patentFile, tbPamPatentOverseasFile);
                    tbPamPatentOverseasFile.setDataId(patentApplyProject.getDisclosureId());
                    tbPamPatentOverseasFile.setCreateBy(userId);
                    tbPamPatentOverseasFile.setUpdateBy(userId);
                    tbPamPatentOverseasFile.setCreateDate(patentFile.getUploadTime());
                    tbPamPatentOverseasFile.setUpdateDate(patentFile.getUploadTime());
                    tbPamPatentOverseasFile.setCreateName(patentFile.getOwnerUserFullName());
                    int insert1 = tbPamPatentOverseasFileMapper.insert(tbPamPatentOverseasFile);
                    if (insert1 != 1) {
                        log.error("保存专利答复文件出错");
                        throw new Exception("保存专利答复文件出错");
                    }
                } else {
                    patentFile.setPatentFileId(IdGen.generateUUID());
                    if (patentFile.getFileType() == 6 || patentFile.getFileType() == 7) {
                        patentFile.setPatentId(patent.getId());
                    } else {
                        patentFile.setDiscId(patentApplyProject.getId());
                    }
                    patentFile.setOwnerAs(String.valueOf(userId));
                    int insert1 = patentFileMapper.insert(patentFile);
                    if (insert1 != 1) {
                        log.error("保存专利申请项目文件出错");
                        throw new Exception("保存专利申请项目文件出错");
                    }
                }
            }
        }

    }
}
